﻿#include "UNodeManager.h"
#include <QMenu>
#include <QDir>
#include <QDebug>
#include "UToolBarManager.h"
#include "Global.h"
#include "UPropertyNode.h"
UNodeManager::UNodeManager(QWidget *parent)
	: QWidget(parent), m_pointManager(new CPointManager)
{
	ui.setupUi(this);
	rootNode = NULL;
	m_pNodeCurr = NULL;
	m_pUAddDevice = nullptr;
}

UNodeManager::~UNodeManager()
{
	delete m_pointManager;
	//if (m_pUAddDevice != nullptr)
	//{
	//	delete m_pUAddDevice;
	//	m_pUAddDevice = nullptr;
	//}
	
}


void UNodeManager::refushUi()
{
	model->removeRow(0);
	model->appendRow(g_pRoot->getItem());
	QModelIndex index = g_pRoot->getItem()->index(); // 获取该 item 对应的 QModelIndex
	ui.treeView->expand(index);
	g_pRoot->init();   //初始化
	m_pNodeCurr = g_pRoot;
	refushMenu();
	emit sign_showCilckedWidget(m_pNodeCurr);
}

void UNodeManager::addNode(CBaseNode * parent)
{
	QString sNodeName = "#" + QString::number(parent->getChildren().size() + 1) + A2T("节点");
	QString sStr = showGetText(this, A2T("添加节点"), A2T("请输入节点名称"), sNodeName);
	if (!sStr.isEmpty())
	{
		if (parent == NULL)
		{
			parent = rootNode;
		}
		CNormalNode* node = new CNormalNode(sStr, generateUniqueId("Node"), "", parent);
		node->showItem(ui.treeView);
		m_pNodeCurr = node;
		// 删除节点操作
		TreeOperation op;
		op.type = EOperationType::enAdd;
		op.node = node;
		op.oldParent = parent;
		m_undoStack.push(op);
		m_redoStack.clear(); // 清空 redo 栈
		refushNode(node);
	}
}

void UNodeManager::addDevice(CBaseNode * parent)
{
	if (parent == NULL)
	{
		parent = rootNode;
	}
	m_pUAddDevice = new UAddDevice(parent, g_pDeviceManager);
	m_pUAddDevice->setAttribute(Qt::WA_DeleteOnClose); // 关闭时自动 delete
	connect(m_pUAddDevice, &UAddDevice::deviceAdded, this, [=](CBaseNode* newDevice) {
		TreeOperation op;
		op.type = EOperationType::enAdd;
		op.node = newDevice;
		op.oldParent = parent;
		m_undoStack.push(op);
		m_redoStack.clear();
		refushNode(newDevice);
	});

	m_pUAddDevice->show();
	
}

void UNodeManager::addMeasurePoint(CBaseNode * parent)
{
	QString sStr = showGetText(this, A2T("添加测点"), A2T("请输入测点名称"));
	if (!sStr.isEmpty())
	{
		if (parent == NULL)
		{
			parent = rootNode;
		}
		CMeasurePoint* node = new CMeasurePoint(sStr, generateUniqueId("Point"), "", parent);
		refushNode(node, 1);
	}
}

void UNodeManager::copyNode(CBaseNode * node)
{
}

void UNodeManager::cutNodes(QVector<CBaseNode*> vecNodes)
{
	m_pVecClipboardNode.clear();
	for (CBaseNode* node : vecNodes)
	{
		if (!node || node == rootNode)
		{
			continue;
		}
		m_pVecClipboardNode.push_back(node);
		m_isCutOperation = true;
	}
	
}


void UNodeManager::pasteNodes(CBaseNode * targetParent)
{
	if (!m_isCutOperation)return;
	//判断targetParent不是m_pVecClipboardNode里面的某一个节点的子节点
	for (CBaseNode* node : m_pVecClipboardNode)
	{
		if (isDescendant(node, targetParent))
		{
			return;
		}
	}
	TreeOperation op;
	op.type = EOperationType::enMove;
	//先获取节点在原父节点下面的序号
	QMap<CBaseNode*, int>mapIndex;
	for (CBaseNode* node : m_pVecClipboardNode)
	{
		CBaseNode* oldParent = node->getParent();
		int oldIndex = oldParent ? oldParent->getChildren().indexOf(node) : -1;
		mapIndex.insert(node, oldIndex);
	}
	for (CBaseNode* node : m_pVecClipboardNode)
	{
		CBaseNode* oldParent = node->getParent();
		// 如果目标父节点无效
		if (!targetParent) break;
		// 获取目标父节点的类型
		int nNodeType = targetParent->getType();
		// 如果目标节点是“设备”或“测点”类型，不允许粘贴，直接返回
		if (nNodeType == CBaseNode::enDevice || nNodeType == CBaseNode::enMeasurePoint) break;
		//剪贴板节点为空，或者目标父节点就是剪贴板节点本身，则不进行任何操作
		if (!node || (targetParent == node)) continue;
		// 从原父节点中移除剪贴板节点
		node->getParent()->removeChild(node);
		// 将剪贴板节点添加到目标父节点下
		int insertIndex = targetParent->getChildren().size(); // 插入末尾
		targetParent->addChild(insertIndex,node);
		m_isCutOperation = false;		

		
		//回退操作记录
		op.nodeList.append(node);
		op.oldParents.append(oldParent);
		op.oldIndexes.append(mapIndex[node]);
		op.newParents.append(targetParent);
		op.newIndexes.append(insertIndex);
	}
	if (!m_isCutOperation)
	{
		m_undoStack.push(op);
		m_redoStack.clear();
		m_pVecClipboardNode.clear();
	}
}
/**
* @ Author: Gaojia
* @ Description:
 删除指定的节点，并将删除操作记录到撤销栈中，清空重做栈。
 如果节点是根节点，操作将不会执行。
 删除操作会移除节点，并保存该操作的信息以便撤销。
*/

void UNodeManager::deleteNode(CBaseNode * node)
{
	if (node == nullptr)
	{
		showMessageBox(this, A2T("警告"), A2T("请先选择节点、设备或者测点"), 1);
		return;
	}
	if (node == g_pRoot)
	{
		showMessageBox(this, A2T("警告"), A2T("根节点不允许删除"), 1);
		return;
	}
	bool bSure = showMessageBox(this, A2T("提示"), A2T("确认删除此节点、设备或者测点吗？"), 1, true);
	if (bSure)
	{
		CBaseNode* pParrent = node->getParent();
		node->deleteNode();
		m_pNodeCurr = pParrent;
		/*CBaseNode* pParrent = node->getParent();
		int index = pParrent->getChildren().indexOf(node);
		pParrent->removeChild(node);
		m_pNodeCurr = pParrent;*/
		refushMenu();
		emit sign_showCilckedWidget(m_pNodeCurr);
		//int index = node->getParent()->getChildren().indexOf(node);
		//// 删除节点操作
		//TreeOperation op;
		//op.type = EOperationType::enDelete;
		//op.node = node;
		//op.oldParent = node->getParent();
		//op.oldIndex = index;
		//node->getParent()->removeChild(node);
		//m_undoStack.push(op);
		//m_redoStack.clear(); // 清空 redo 栈
		//refushNode(node,1);
	}
}


void UNodeManager::initUI()
{
	ui.treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.treeView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);  // 禁用编辑
	//ui.treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); // 支持 Ctrl 和 Shift 多选
	ui.treeView->header()->hide();
	model = new QStandardItemModel(this);
	ui.treeView->setModel(model);
	ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	ui.treeView->viewport()->installEventFilter(this);
	connectTree();
	QString exePath = QCoreApplication::applicationDirPath();
	// 构建配置文件的完整路径
	QString configFilePath = QDir(exePath).filePath("config.xml");
	QAction *pAdd=g_pToolBarMang->addAction(UToolBarManager::Device, A2T("添加节点"), QIcon(":/SmartControl/Resource/toolbar/add.png"));
	QAction *pAddDevice=g_pToolBarMang->addAction(UToolBarManager::Device, A2T("添加设备"), QIcon(":/SmartControl/Resource/toolbar/adddevice.png"));
	QAction *pAddPoint = g_pToolBarMang->addAction(UToolBarManager::Device, A2T("添加测点"), QIcon(":/SmartControl/Resource/toolbar/addpoint.png"));
	QAction *pDelete=g_pToolBarMang->addAction(UToolBarManager::Device, A2T("删除"), QIcon(":/SmartControl/Resource/toolbar/delete.png"));
	g_pToolBarMang->addSeparator(UToolBarManager::Device);
	QAction *pRun=g_pToolBarMang->addAction(UToolBarManager::Device, A2T("运行"), QIcon(":/SmartControl/Resource/toolbar/run.png"));
	QAction *pStop=g_pToolBarMang->addAction(UToolBarManager::Device, A2T("停止"), QIcon(":/SmartControl/Resource/toolbar/stop.png"));
	g_pToolBarMang->addSeparator(UToolBarManager::Device);
	g_pToolBarMang->setToolBtn(UToolBarManager::Device, 1);
	ui.toolButton->setIcon(QIcon(":/SmartControl/Resource/toolbar/add_2.png"));
	ui.toolButton_2->setIcon(QIcon(":/SmartControl/Resource/toolbar/adddevice_2.png"));
	ui.toolButton_4->setIcon(QIcon(":/SmartControl/Resource/toolbar/delete_2.png"));
	ui.toolButton->setIconSize(QSize(30, 30));
	ui.toolButton_2->setIconSize(QSize(30, 30));
	ui.toolButton_4->setIconSize(QSize(30, 30));
	ui.toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
	ui.toolButton_2->setToolButtonStyle(Qt::ToolButtonIconOnly);
	ui.toolButton_4->setToolButtonStyle(Qt::ToolButtonIconOnly);
	connect(ui.toolButton, SIGNAL(clicked()), this, SLOT(slot_addNode()));
	connect(ui.toolButton_2, SIGNAL(clicked()), this, SLOT(slot_addPage()));
	//connect(ui.toolButton, SIGNAL(clicked()), this, SLOT(slot_addPoint()));
	connect(ui.toolButton_4, SIGNAL(clicked()), this, SLOT(slot_deleteNode()));

	connect(pAdd, &QAction::triggered, this, &UNodeManager::slot_addNode);
	connect(pAddDevice, &QAction::triggered, this, &UNodeManager::slot_addPage);
	connect(pAddPoint, &QAction::triggered, this, &UNodeManager::slot_addPoint);
	connect(pDelete, &QAction::triggered, this, &UNodeManager::slot_deleteNode);
	emit sign_showCilckedWidget(g_pRoot);
}

void UNodeManager::setCurrNode(CBaseNode * node, CBaseNode* child)
{
	m_pNodeCurr = node;
	m_pNodeChild = child;
	refushMenu();
}

void UNodeManager::showContextMenu(CBaseNode * node, const QPoint & globalPos)
{
	QMenu* menu = new QMenu(this);

	// 通用菜单
	menu->addAction(A2T("重命名"), this, [this, node]() { renameNode(node); });
	menu->addSeparator();
	// 删除操作
	switch (node->getType()) {
	case CBaseNode::enRoot:
		createRootMenu(menu, node);
		break;
	case CBaseNode::enNode:
		createNodeMenu(menu, node);
		break;
	case CBaseNode::enDevice:
		createDeviceMenu(menu, node);
		break;
	case CBaseNode::enMeasurePoint:
		createPointMenu(menu, node);
		break;
	default:
		break;
	}

	// 私有菜单（设备、测点）
	if (node->getType() == CBaseNode::enDevice) {
		if (auto devMenu = g_pDeviceManager->createDeviceMenu(static_cast<CBaseDevice*>(node), this)) {
			menu->addMenu(devMenu);
		}
	}

	if (node->getType() == CBaseNode::enMeasurePoint) {
		if (auto ptMenu = m_pointManager->createMenu(static_cast<CMeasurePoint*>(node), this)) {
			menu->addMenu(ptMenu);
		}
	}

	menu->exec(globalPos);
	delete menu;
}

void UNodeManager::showContextLeft(CBaseNode * node, const QPoint & globalPos)
{
	QList<CMeasurePoint*>pVecMeasurePoint;
	// 删除操作
	switch (node->getType()) 
	{
	case CBaseNode::enRoot:
		emit sign_showCilckedWidget(node);
		m_pNodeCurr = node;
		//m_pConfig->setParent(ui.t)
		break;
	case CBaseNode::enNode:
		emit sign_showCilckedWidget(node);
		m_pNodeCurr = node;
		break;
	case CBaseNode::enDevice:
		emit sign_showCilckedWidget(node);
		m_pNodeCurr = node;
		//m_pConfig->show();
		break;
	case CBaseNode::enMeasurePoint:
		emit sign_showCilckedWidget(node);
		m_pNodeCurr = node;
		break;
	default:
		break;
	}
}

void UNodeManager::connectTree()
{
	ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui.treeView, &QTreeView::customContextMenuRequested,this, &UNodeManager::onTreeContextMenuRequested);
}

void UNodeManager::onTreeContextMenuRequested(const QPoint & pos)
{
	m_pNodeChild = nullptr;
	QModelIndex index = ui.treeView->indexAt(pos);
	if (!index.isValid())
	{
		refushMenu();
		createNullMenu(ui.treeView->viewport()->mapToGlobal(pos));
	}
	else
	{
		QStandardItem* item = model->itemFromIndex(index);
		if (!item) return;
		CBaseNode* node = reinterpret_cast<CBaseNode*>(item->data(Qt::UserRole).value<void*>());
		if (!node)return;
		m_pNodeCurr = node;
		if (node->getType() == CBaseNode::enRoot)
		{
			refushMenu();
		}
		else
		{
			refushMenu();
		}
		showContextMenu(node, ui.treeView->viewport()->mapToGlobal(pos));
	}
}

void UNodeManager::renameNode(CBaseNode* node)
{
	if (!node) return;

	QStandardItem* item = node->getItem();
	if (!item) return;

	QString oldName = node->getName(); // 记录旧名称
	// 允许临时编辑
	ui.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);

	QModelIndex index = item->index();
	ui.treeView->edit(index);
	// 防止多次连接 itemChanged（避免重复触发）
	static QMetaObject::Connection conn;
	if (conn) QObject::disconnect(conn);
	// 监听编辑完成后恢复禁止编辑
	conn=connect(model, &QStandardItemModel::itemChanged, this, [=](QStandardItem* changedItem)
	{
		if (changedItem == item) 
		{
			node->setName(item->text());  // 同步修改到 node
			QString newName = item->text();
			// 只有真正修改了名称才处理
			if (newName != oldName) 
			{
				// 添加到撤销栈
				TreeOperation op;
				op.type = EOperationType::enReName;
				op.node = node;
				op.oldName = oldName;
				op.newName = newName;
				m_undoStack.push(op);
				m_redoStack.clear(); // 清空 redo 栈
			}

			ui.treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); // 编辑完成后再次禁用
			QObject::disconnect(conn); // 编辑完后断开连接

		}
	});

}

void UNodeManager::slot_addNode()
{
	if (m_pNodeCurr == NULL)
	{
		m_pNodeCurr = rootNode;
	}
	if (m_pNodeCurr->getType() == CBaseNode::enNode|| m_pNodeCurr->getType() == CBaseNode::enRoot)
	{
		addNode(m_pNodeCurr);
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请选择一个节点"), 1);
	}
}

void UNodeManager::slot_addPage()
{
	if (m_pNodeCurr == NULL)
	{
		m_pNodeCurr = rootNode;
	}
	if (m_pNodeCurr->getType() == CBaseNode::enNode || m_pNodeCurr->getType() == CBaseNode::enRoot)
	{
		addDevice(m_pNodeCurr);
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请选择一个节点"), 1);
	}
}

void UNodeManager::slot_addPoint()
{
	if (m_pNodeCurr == NULL)
	{
		m_pNodeCurr = rootNode;
	}
	if (m_pNodeCurr->getType() == CBaseNode::enNode || m_pNodeCurr->getType() == CBaseNode::enRoot)
	{
		addMeasurePoint(m_pNodeCurr);
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请选择一个节点"), 1);
	}
}

void UNodeManager::slot_deleteNode()
{
	if (m_pNodeChild == nullptr)
	{
		deleteNode(m_pNodeCurr);
	}
	else
	{
		deleteNode(m_pNodeChild);
		m_pNodeChild = nullptr;
	}
}

void UNodeManager::createNullMenu(const QPoint& globalPos)
{
	QMenu* menu = new QMenu(this);

	// 通用菜单
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"), A2T("添加子节点(N)..."), this, [=]()
		{ 
			if (m_pNodeCurr == nullptr)
			{
				m_pNodeCurr = g_pRoot;
			}
			addNode(m_pNodeCurr); 
		});
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/adddevice.png"), A2T("添加设备(D)..."), this, [=]()
		{ 
			if (m_pNodeCurr == nullptr)
			{
				m_pNodeCurr = g_pRoot;
			}
			addDevice(m_pNodeCurr); 
		});
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/addpoint.png"), A2T("添加测点(P)..."), this, [=]()
		{ 
			if (m_pNodeCurr == nullptr)
			{
				m_pNodeCurr = g_pRoot;
			}
			addMeasurePoint(m_pNodeCurr); 
		});
	menu->addSeparator();
	menu->addAction(A2T("属性"), this, [=]()
		{
			if (m_pNodeCurr == nullptr)
			{
				m_pNodeCurr = g_pRoot;
			}
			UPropertyNode dlg(m_pNodeCurr, this);  // this 是父窗口
			dlg.exec();
		});
	menu->exec(globalPos);
	delete menu;
}

void UNodeManager::createRootMenu(QMenu * menu, CBaseNode * node)
{
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"),A2T("添加子节点(N)..."), this, [=]() { addNode(node); });
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/adddevice.png"), A2T("添加设备(D)..."), this, [=]() {addDevice(node); });
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/addpoint.png"), A2T("添加测点(P)..."), this, [=]() {addMeasurePoint(node); });
	menu->addSeparator();
	/*if (m_isCutOperation)
	{
		menu->addAction(A2T("粘贴"), this, [=]() { pasteNodes(node); });
	}*/
	menu->addAction(A2T("属性"), this, [=]()
		{
			if (m_pNodeCurr == nullptr)
			{
				m_pNodeCurr = g_pRoot;
			}
			UPropertyNode dlg(m_pNodeCurr, this);  // this 是父窗口
			dlg.exec();
		});
}

void UNodeManager::createNodeMenu(QMenu * menu, CBaseNode * node)
{
	QVector<CBaseNode *>vecNodes;
	vecNodes.push_back(node);
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"), A2T("添加子节点(N)..."), this, [=]() { addNode(node); });
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/adddevice.png"), A2T("添加设备(D)..."), this, [=]() {addDevice(node); });
	//menu->addAction(QIcon(":/SmartControl/Resource/toolbar/addpoint.png"), A2T("添加测点(P)..."), this, [=]() {addMeasurePoint(node); });
	menu->addSeparator();
	/*if (m_isCutOperation)
	{
		menu->addAction(A2T("粘贴"), this, [=]() { pasteNodes(node); });
	}*/
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/delete.png"),A2T("删除节点"), this, [=]() { m_pNodeCurr = node; slot_deleteNode(); });
	menu->addSeparator();
	menu->addAction(A2T("属性"), this, [=]()
		{
			if (m_pNodeCurr == nullptr)
			{
				m_pNodeCurr = g_pRoot;
			}
			UPropertyNode dlg(m_pNodeCurr, this);  // this 是父窗口
			dlg.exec();
		});
}

void UNodeManager::createDeviceMenu(QMenu * menu, CBaseNode * node)
{
	QVector<CBaseNode *>vecNodes;
	vecNodes.push_back(node);
	menu->addAction(A2T("剪切"), this, [=]() { cutNodes(vecNodes); });
	menu->addAction(A2T("删除设备"), this, [=]() { deleteNode(static_cast<CBaseDevice*>(node)); });
}

void UNodeManager::createPointMenu(QMenu * menu, CBaseNode * node)
{
	QVector<CBaseNode *>vecNodes;
	vecNodes.push_back(node);
	menu->addAction(A2T("剪切"), this, [=]() { cutNodes(vecNodes); });
	menu->addAction(A2T("删除测点"), this, [=]() { deleteNode(static_cast<CMeasurePoint*>(node)); });
}

void UNodeManager::keyPressEvent(QKeyEvent* event)
{
	if (event->modifiers() & Qt::ControlModifier) 
	{
		if (event->key() == Qt::Key_X) 
		{
			QVector<CBaseNode *>vecNode = getSelectedNodes();
			cutNodes(vecNode);
			//// 复制操作
			//QModelIndex index = ui.treeView->currentIndex();
			//if (index.isValid()) 
			//{
			//	QStandardItem* item = model->itemFromIndex(index);
			//	if (item) 
			//	{
			//		CBaseNode* node = static_cast<CBaseNode*>(item->data(Qt::UserRole).value<void*>());
			//		cutNode(node); // 你需要实现这个函数
			//	}
			//}
		}
		else if (event->key() == Qt::Key_V) 
		{
			// 粘贴操作
			QModelIndex index = ui.treeView->currentIndex();
			if (index.isValid()) 
			{
				QStandardItem* item = model->itemFromIndex(index);
				if (item) 
				{
					CBaseNode* node = static_cast<CBaseNode*>(item->data(Qt::UserRole).value<void*>());
					pasteNodes(node);
				}
			}
		}
		if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Z)
			undo(); // 撤销操作
		else if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Y)
			redo(); // 重做操作
	}
	else if (event->key() == Qt::Key_Delete)
	{
		// 粘贴操作
		QModelIndex index = ui.treeView->currentIndex();
		if (index.isValid())
		{
			QStandardItem* item = model->itemFromIndex(index);
			if (item)
			{
				CBaseNode* node = static_cast<CBaseNode*>(item->data(Qt::UserRole).value<void*>());
				deleteNode(node);
			}
		}
	}
	QWidget::keyPressEvent(event); // 保留默认处理
}

QVector<CBaseNode*> UNodeManager::getSelectedNodes()
{
	QVector<CBaseNode*> selectedNodes;
	QModelIndexList selectedIndexes = ui.treeView->selectionModel()->selectedIndexes();
	QSet<CBaseNode*> uniqueSet;

	for (const QModelIndex& index : selectedIndexes)
	{
		QStandardItem* item = model->itemFromIndex(index);
		if (!item) continue;

		QVariant data = item->data(Qt::UserRole);
		CBaseNode* node = static_cast<CBaseNode*>(data.value<void*>());

		if (node && !uniqueSet.contains(node))
		{
			selectedNodes.append(node);
			uniqueSet.insert(node); // 去重
		}
	}
	return selectedNodes;
}


bool UNodeManager::isDescendant(CBaseNode* parent, CBaseNode* child)
{
	if (!parent || !child) return false;

	// 直接子节点里查找
	const QVector<CBaseNode*>& children = parent->getChildren(); // 假设你有这个函数
	for (CBaseNode* node : children)
	{
		if (node == child)
			return true;
		// 递归地往下找
		if (isDescendant(node, child))
			return true;
	}
	return false;
}

// 撤销操作
void UNodeManager::undo()
{
	if (m_undoStack.isEmpty()) return;

	TreeOperation op = m_undoStack.pop();
	switch (op.type)
	{
	case EOperationType::enMove:
	{
		for (int i = 0; i < op.nodeList.size(); ++i)
		{
			op.newParents[i]->removeChild(op.nodeList[i]);
			// 将剪贴板节点添加到目标父节点下
			op.oldParents[i]->addChild(op.oldIndexes[i], op.nodeList[i]);
		}
		break;
	}
	case EOperationType::enAdd:
	{
		op.node->getParent()->removeChild(op.node);
		break;
	}
	case EOperationType::enDelete:
	{
		op.oldParent->addChild(op.oldIndex,op.node);
		break;
	}
	case EOperationType::enReName:
	{
		op.node->setName(op.oldName);
		op.node->setItemName(op.oldName);
		break;
	}
	}
	m_redoStack.push(op);
}

void UNodeManager::mousePressEvent(QMouseEvent * event)
{
	if (event->button() == Qt::LeftButton) 
	{
		// 这是鼠标左键点击
		qDebug() << "左键点击：" << event->pos();
	}
}

/**
* @ Author: Gaojia
* @ Description: 刷新当前节点显示  0当前  1上一级
*/
void UNodeManager::refushNode(CBaseNode * node,int nType)
{
	m_pNodeCurr = node->getParent();
	emit sign_showCilckedWidget(m_pNodeCurr, node);
	m_pNodeCurr->showItem(ui.treeView);
}

void UNodeManager::refushMenu()
{
	if (m_pNodeCurr == nullptr)
	{
		m_pNodeCurr = g_pRoot;
	}
	m_pNodeCurr->showItem(ui.treeView);
	if (m_pNodeCurr->getType() == CBaseNode::enRoot && m_pNodeChild == nullptr)
	{
		g_pToolBarMang->setToolBtn(UToolBarManager::Device, 1);
	}
	else
	{
		g_pToolBarMang->setToolBtn(UToolBarManager::Device, 0);
	}
}

bool UNodeManager::eventFilter(QObject *obj, QEvent *event)
{
	if (obj == ui.treeView->viewport() && event->type() == QEvent::MouseButtonPress) 
	{
		QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

		if (mouseEvent->button() == Qt::LeftButton) 
		{
			onTreeLeftClieck(mouseEvent->pos());
		}
		if (mouseEvent->button() == Qt::RightButton)
		{
			onTreeRightClieck(mouseEvent->pos());
		}
	}

	return QObject::eventFilter(obj, event); // 交给默认处理
}

void UNodeManager::onTreeLeftClieck(const QPoint & pos)
{
	m_pNodeChild = nullptr;
	QModelIndex index = ui.treeView->indexAt(pos);
	if (!index.isValid())
	{
		refushMenu(); 
		return;
	}
	QStandardItem* item = model->itemFromIndex(index);
	if (!item)
	{
		refushMenu();
		return;
	}
	CBaseNode* node = reinterpret_cast<CBaseNode*>(item->data(Qt::UserRole).value<void*>());
	if (!node)
	{
		refushMenu();
		return;
	}
	showContextLeft(node, ui.treeView->viewport()->mapToGlobal(pos));
	refushMenu();
}

void UNodeManager::onTreeRightClieck(const QPoint& pos)
{
}


// 重做操作
void UNodeManager::redo()
{
	if (m_redoStack.isEmpty()) return;

	TreeOperation op = m_redoStack.pop();
	switch (op.type)
	{
	case EOperationType::enMove:
	{
		for (int i = 0; i < op.nodeList.size(); ++i)
		{
			op.oldParents[i]->removeChild(op.nodeList[i]);
			op.newParents[i]->addChild(op.newIndexes[i], op.nodeList[i]);
		}
		break;
	}
	case EOperationType::enAdd:
	{
		op.node->getParent()->addChild(op.node);
		break;
	}
	case EOperationType::enDelete:
	{
		op.oldParent->removeChild(op.node);
		break;
	}
	case EOperationType::enReName:
	{
		op.node->setName(op.newName);
		op.node->setItemName(op.newName);
		break;
	}
	}
	m_undoStack.push(op);
}
